package com.dongway.netcondition.web;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dongway.core.web.AbstractBaseController;
import com.dongway.core.web.SessionCodes;
import com.dongway.netcondition.model.User;
import com.dongway.netcondition.service.UserService;

@Controller
public class AuthController extends AbstractBaseController {

    @Autowired
    private UserService userService;


    @RequestMapping("/login.htm")
    public String loginPage() {
        return "net/login";
    }
    
    
    @RequestMapping("/register.htm")
    public String registerPage() {
        return "net/register";
    }


    @RequestMapping("logout.htm")
    public String logout(ModelMap modelMap) {
        org.apache.shiro.SecurityUtils.getSubject().logout();
        return redirect("/login.htm");
    }
    
    
    @RequestMapping("login.json")
    @ResponseBody
    public Object login(User user, HttpSession session) {
        try {
            userService.login(user);
            session.setAttribute(SessionCodes.SESSION_USER, user.getLogin());
            Subject currentUser = SecurityUtils.getSubject();
            return JsonSuccess(currentUser != null);
        } catch (Exception e) {
            return JsonFailed(e);
        }
    }
    
    @RequestMapping("register.json")
    @ResponseBody
    public Object register(User user) {
        try {
            userService.register(user);
            return JsonSuccess(user);
        } catch (Exception e) {
            return JsonFailed(e);
        }
    }
}
